﻿using PureMVC.Patterns.Command;
using PureMVC.Patterns.Facade;
using PureMVC.Patterns.Proxy;
using Rzc.DevPlat.Controller;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rzc.DevPlat
{
    public class ApplicationFacade:Facade
    {
        readonly string defaultNameSpace = "Rzc.DevPlat";
        private static ApplicationFacade m_ApplicationFacade;
        public static ApplicationFacade Instance
        {
            get
            {
                if(m_ApplicationFacade == null)
                {
                    m_ApplicationFacade = new ApplicationFacade();
                }
                return m_ApplicationFacade;
            }
        }
        private ApplicationFacade()
        {
            var types = GetTypes(defaultNameSpace);
            foreach(var t in types)
            {
                if (t.IsSubclassOf(typeof(SimpleCommand)))
                {
                    RegisterCommand(t.FullName,()=>Activator.CreateInstance(t) as SimpleCommand);
                }
            }
            RegisterCommand("StartupCommand", () => new StartupCommand());
        }

        Type[] GetTypes(string typeNameSpaceStart)
        {
            var assemblys = AppDomain.CurrentDomain.GetAssemblies();
            List<Type> types = new List<Type>();
            foreach (var assembly in assemblys)
                foreach (Type type in assembly.GetTypes())
                {
                    if (!string.IsNullOrEmpty(type.Namespace) &&type.Namespace.StartsWith(typeNameSpaceStart))
                    {
                        types.Add(type);
                    }
                }
            return types.ToArray();
        }
    }
}
